package controllers

import (
	"fmt"
	"ltbz/cultural_tourism_api/models"
	"ltbz/cultural_tourism_api/services"
	"ltbz/cultural_tourism_api/utils"
	"os"
	"path"
	"time"
)

// 共用接口模块
type CommonController struct {
	BaseAuthController
}

// @Title 图片上传
// @Description 图片上传
// @Param File query string false "图片上传参数"
// @Success 200
// @router /image/upload [post]
func (this *CommonController) Upload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	f, h, err := this.GetFile("File")
	if err != nil {
		br.Msg = "获取资源信息失败"
		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
		return
	}
	ext := path.Ext(h.Filename)
	var randStr, fileName string
	randStr = utils.GetRandStringNoSpecialChar(16)
	fileName = randStr + ext

	defer f.Close() //关闭上传文件

	dir := utils.GetCurrentAbPath()
	tempPath := dir + `/static/` + fileName
	err = this.SaveToFile("File", tempPath)
	if err != nil {
		br.Msg = "文件上传失败"
		br.ErrMsg = "保存临时文件失败，Err:" + err.Error() + ";tempPath:" + tempPath
		return
	}

	var fileHost, resourceUrl string

	if utils.ObjectStorageClient == "minio" {
		fmt.Println(fileName)
		fmt.Println(tempPath)

		resourceUrl, err = services.UploadImgToMinIo(fileName, tempPath)
		if err != nil {
			br.Msg = "文件上传失败"
			br.ErrMsg = "文件上传失败，Err:" + err.Error()
			return
		}
	} else if utils.ObjectStorageClient == "oss" {
		saveToOssPath := "static/images/" + time.Now().Format("20060102") + "/" + fileName
		err = services.UploadFileToAliyun(tempPath, saveToOssPath)
		if err != nil {
			br.Msg = "文件上传失败"
			br.ErrMsg = "文件上传失败，Err:" + err.Error()
			return
		}
		fileHost = "https://cwdos.cxyongding.com/"

		resourceUrl = fileHost + saveToOssPath
	} else {
		br.Msg = "对象存储客户端配置错误,请联系管理员"
		return
	}

	defer func() {
		os.Remove(tempPath)
	}()

	resp := new(models.ImageUploadResp)
	resp.ResourceUrl = resourceUrl
	resp.FileName = fileName
	br.Msg = "上传成功"
	br.Ret = 200
	br.Data = resp
	return
}
